﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.Entity.Entity;
using Jinjia.Approve.IRepository;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.IService.JJFlow.Action;
using Jinjia.Approve.Model.VM;
using Jinjia.Approve.Model.VM.JJFlow;
using Jinjia.Approve.Model.VM.JJFlow.DTO;

namespace Jinjia.Approve.Service.JJFlow.Action
{
    public class JJFLowActionCommon : JJFlowActionGoTo, IJJFLowActionCommon
    {
        private readonly IJJFlowClientService _jjFlowClientService;
        private readonly IFlowNodeRepository _flowNodeRepository;
        private readonly IFlowInstanceEmpRepository _flowInstanceEmpRepository;
        private readonly IErpaViewedLogRepository _erpaViewedLogRepository;

        public JJFLowActionCommon(IJJFlowInstanceService jjFlowInstanceService,
            IJJFlowTrackService jjFlowTrackService,
            IJJFlowClientService jjFlowClientService,
            IFlowNodeRepository flowNodeRepository,
            IFlowInstanceEmpRepository flowInstanceEmpRepository,
            IErpaViewedLogRepository erpaViewedLogRepository) : base(jjFlowInstanceService,
            jjFlowTrackService)
        {
            _jjFlowClientService = jjFlowClientService;
            _flowNodeRepository = flowNodeRepository;
            _flowInstanceEmpRepository = flowInstanceEmpRepository;
            _erpaViewedLogRepository = erpaViewedLogRepository;
        }

        public async Task<List<JjFlowTrackVM>> GetFlowTrackList(string biz_order_id, string modular_key)
        {
            var instance_info = await _jjFlowClientService.GetInstanceInfo(modular_key, biz_order_id);
            if (instance_info == null)
            {
                return new List<JjFlowTrackVM>();
            }

            var flow_instance_id = instance_info.Id;
            //之前拒绝驳回的轨迹
            var history_list = (await _jjFlowTrackService.GetFlowTrackHistory(biz_order_id, modular_key, flow_instance_id))
                .OrderByDescending(x => x.op_time).ToList();
            //当前的轨迹
            var result = (await _jjFlowTrackService.GetFlowTrackById(flow_instance_id))
                .OrderByDescending(x => x.node_status_type)
                .ThenByDescending(x => x.sequence)
                .ThenByDescending(x => x.op_time)
                .ToList();

            var historyResult = result.Where(o => o.node_status_type == 0).ToList();

            historyResult.ForEach(item =>
            {
                result.Remove(item);
            });

            result.AddRange(historyResult.OrderByDescending(o => o.op_time));

            //.ThenByDescending(x=>x.sequence).
            if (result.Count > 0 && history_list.Count > 0)
            {
                var current_id = result.First().instance_id;
                history_list = history_list.Where(x => x.instance_id != current_id).ToList();
                result.AddRange(history_list);
            }

            result.First().emp_name = "完成";

            var model = result.FirstOrDefault(x => x.node_status_type == 1); //当前
            var new_model = result.LastOrDefault(x => x.node_status_type == 2); //未来第一个
            if (instance_info.Status == "0")
            {
                foreach (var item in result)
                {
                    if (item.Equals(model))
                    {
                        item.node_status_type = 0;
                    }
                    else if (item.Equals(new_model))
                    {
                        item.node_status_type = 1;
                        item.action_type_name = "待审核";
                    }
                }
            }

            return result;
        }

        public async Task<List<EmpInfo>> GetCompletedNodeList(JjFlowInstanceVM instance)
        {
            var all_planned_nodes = await _flowNodeRepository.GetNodesPlan(instance.Id);
            var instance_user = await _flowInstanceEmpRepository.GetInstanceUserInfo(instance.Id, instance.TemplateId);
            var instance_user_complete = instance_user.Where(x => x.is_complete == 1).ToList();
            foreach (var item in instance_user_complete)
            {
                //此处需要对返回节点id做处理，否则调用退回接口会导致退回节点异常
                var current_node_index = all_planned_nodes.FindIndex(m => m.id == item.node_id);
                var back_node = all_planned_nodes[current_node_index - 1];
                item.node_name = all_planned_nodes.FirstOrDefault(n => n.id == item.node_id)?.node_name;// 必须在node_id更新前
                item.node_id = back_node.id;
            }

            return instance_user_complete;
        }

        public async Task<int> RecordViewLog(string doc_model, string biz_order_id, int user_id)
        {
            var tbl = await _erpaViewedLogRepository.GetViewLogByModularKeyAndBIdAndUserId(doc_model, biz_order_id, user_id);

            if (tbl != null)
            {
                tbl.total += 1;
            }
            else
            {
                tbl = new erpa_viewed_log_tbl
                {
                    create_user_id = user_id,
                    update_user_id = user_id,
                    total = 1,
                    doc_model = doc_model,
                    biz_order_id = biz_order_id
                };
            }

            var result = await _erpaViewedLogRepository.Save(tbl);
            return result;
        }

        public async Task<List<ErpaViewedLogViewModel>> GetViewedLog(string doc_model, string biz_order_id)
        {
            var viewLogByModularKeyAndBId = await _erpaViewedLogRepository.GetViewLogByModularKeyAndBId(doc_model, biz_order_id);
            return viewLogByModularKeyAndBId;
        }
    }
}